package com.mingdao.lhy.biz;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfStamper;
import com.mingdao.lhy.constant.Constant;
import com.mingdao.lhy.pojo.HighSchoolWish;
import com.mingdao.lhy.pojo.SignUpStudent;
import com.mingdao.lhy.pojo.WishAll;
import com.mingdao.lhy.pojo.WishFive;
import com.mingdao.lhy.pojo.WishFour;
import com.mingdao.lhy.pojo.WishOne;
import com.mingdao.lhy.pojo.WishSix;
import com.mingdao.lhy.pojo.WishThree;
import com.mingdao.lhy.pojo.WishTwo;
import com.mingdao.lhy.service.WishFillingService;

@Component
public class WishFillingBiz {

	@Autowired
	private WishFillingService wishFillingService;

	/**
	 * 一类体制志愿： 前提是一类体制学生和普通学生的彝文加试成绩大于等于30的学生，都要根据考生户籍所在县市分县市单独判断。
	 * 一类志愿学样选择，从gzdm.ylmsjh大于0的学校。
	 * 
	 */
	public Boolean isOneClassOfSystems(SignUpStudent student) {

		if (null == student || student.getJs().isEmpty()) {
			return false;
		}
		String ddks = student.getDdks();
		if (null == ddks || ddks.isEmpty()) {
			return false;
		}
		String js = student.getJs();
		if (js.isEmpty()) {
			return false;
		}
		/**
		 * 如果不是一类体制学生（2），或者加试分数小于30的没有资格报名一类体制学校 TODO js加试分从哪里获取？？？
		 */
		// if (!"2".equals(ddks.substring(1, 1)) || (Double.parseDouble(js) < 30)) {
		String ddksTmp = ddks.substring(0, 1);
		if (!"2".equals(ddksTmp)) {
			return false;
		}

		return true;
	}

	public void getHighSchoolByJdd(String jdd) {

	}

	/**
	 * 根据学生户籍地信息取一类体制学校
	 * 
	 * @param student
	 * @return
	 */
	public String[] getOneClassSchool(SignUpStudent student) {
		Map<String, String> xxdms = new HashMap<String, String>();
		List<String> returnResult = new LinkedList<String>();

		if (null == student.getHjd()) {
			return null;
		}
		String hjd = student.getHjd().substring(0, 6);// 513401
		if (null != Constant.puge_xichang.get(hjd)) {
			xxdms.put("7101009", hjd);
			/**
			 * 考生是普格、西昌籍
			 */

		} else if (null != Constant.dongwuxian.get(hjd)) {
			xxdms.put("7111002", hjd);
			/**
			 * 考生是布拖、金阳、雷波、美姑、昭觉籍
			 */
		} else if (null != Constant.yuexi_ganluo_xide.get(hjd)) {
			xxdms.put("7112002", hjd);
			xxdms.put("7112003", hjd); //20190624新增喜德瓦尔中学高中部

			/**
			 * 考生是越西、甘洛、喜德籍
			 */
		} else if (null != Constant.yanyuan_muli.get(hjd)) {
			xxdms.put("7103002", hjd);
			/**
			 * 考生是盐源、木里籍
			 */
		} else if (null != Constant.dc_mn_hl_hd_nn.get(hjd)) {
			xxdms.put("7112002", hjd);
			xxdms.put("7101009", hjd);
			xxdms.put("7111002", hjd);
			xxdms.put("7103002", hjd);
			/**
			 * 考生是德昌、冕宁、会理、会东、宁南籍
			 */
			Set<Entry<String, String>> eSet = xxdms.entrySet();
			Iterator<Entry<String, String>> it3 = eSet.iterator();
			while (it3.hasNext()) {
				returnResult.add(it3.next().getKey());
			}
			return returnResult.toArray(new String[returnResult.size()]);
		}

		String jdd = student.getJdd();// 513401;513402
		if (null != Constant.puge_xichang.get(jdd)) {
			xxdms.put("7101009", jdd);
			/**
			 * 考生就读地是普格、西昌
			 */

		} else if (null != Constant.dongwuxian.get(jdd)) {
			xxdms.put("7111002", jdd);
			/**
			 * 考生就读地是布拖、金阳、雷波、美姑、昭觉
			 */
		} else if (null != Constant.yuexi_ganluo_xide.get(jdd)) {
			xxdms.put("7112002", jdd);
			/**
			 * 考生就读地是越西、甘洛、喜德
			 */
		} else if (null != Constant.yanyuan_muli.get(jdd)) {
			xxdms.put("7103002", jdd);
			/**
			 * 考生是盐源、木里籍
			 */

		} else if (null != Constant.dc_mn_hl_hd_nn.get(jdd)) {
			xxdms.put("7112002", jdd);
			xxdms.put("7101009", jdd);
			xxdms.put("7111002", jdd);
			xxdms.put("7103002", jdd);
			/**
			 * 考生就读地是德昌、冕宁、会理、会东、宁南
			 */

		}

		if (xxdms.size() == 0) {
			return new String[] { "7112002", "7101009", "7111002", "7103002" };
		} else {
			Set<Entry<String, String>> eSet = xxdms.entrySet();
			Iterator<Entry<String, String>> it3 = eSet.iterator();
			while (it3.hasNext()) {
				returnResult.add(it3.next().getKey());
			}
		}
		String[] keys = returnResult.toArray(new String[returnResult.size()]);
		return keys;
	}

	/**
	 * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
	 * 
	 * @param nowTime
	 *            当前时间
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @return
	 * @author jqlin
	 */
	public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
		if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {
			return true;
		}

		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);

		Calendar begin = Calendar.getInstance();
		begin.setTime(startTime);

		Calendar end = Calendar.getInstance();
		end.setTime(endTime);

		if (date.after(begin) && date.before(end)) {
			return true;
		} else {
			return false;
		}
	}

	public WishAll getWishByStudent(SignUpStudent dbStudent) {
		/**
		 * 取第一批次志愿学校
		 */
		WishOne wishOne = wishFillingService.getWishOneSchool(dbStudent);

		/**
		 * 取第二批次志愿学校 TODO
		 */
		WishTwo wishTwo = wishFillingService.getWishTwoSchool(dbStudent);

		/**
		 * 取第三批次志愿学校 TODO
		 */
		WishThree wishThree = wishFillingService.getWishThreeSchool(dbStudent);

		/**
		 * 取第四批次志愿学校
		 */
		WishFour wishFour = wishFillingService.getWishFourSchool(dbStudent);

		/**
		 * 取第五批次志愿学校
		 */
		WishFive wishFive = wishFillingService.getWishFiveSchool(dbStudent);

		/**
		 * 取第六批次志愿学校
		 */
		WishSix wishSix = wishFillingService.getWishSixSchool(dbStudent);

		WishAll wishAll = new WishAll();
		wishAll.setWishOne(wishOne);
		wishAll.setWishTwo(wishTwo);
		wishAll.setWishThree(wishThree);
		wishAll.setWishFour(wishFour);
		wishAll.setWishFive(wishFive);
		wishAll.setWishSix(wishSix);
		return wishAll;

	}

	/**
	 * 将学生报名基本信息设置到志愿数据中
	 * 
	 * @param signUpStudent
	 * @param highSchoolWish
	 * @return
	 */
	public HighSchoolWish setHighSchoolWish(SignUpStudent signUpStudent, HighSchoolWish highSchoolWish) {
		/**
		 * 身份证号
		 */
		highSchoolWish.setSfzh(signUpStudent.getSfzh());
		/**
		 * 网报序号
		 */
		highSchoolWish.setWbxh(signUpStudent.getWbxh());
		/**
		 * 姓名
		 */
		highSchoolWish.setXm(signUpStudent.getXm());
		/**
		 * 报名号
		 */
		highSchoolWish.setBmh(signUpStudent.getBmh());
		/**
		 * 班级号
		 */
		highSchoolWish.setBjdm(signUpStudent.getBjdm());
		/**
		 * 毕业中学代码
		 */
		highSchoolWish.setByzxdm(signUpStudent.getByzxdm());

		return highSchoolWish;
	}

	/**
	 * 检查无效的志愿数据
	 * 
	 * @param signUpStudent
	 * @param highSchoolWish
	 * @return
	 */
	public HighSchoolWish checkHighSchoolWish(HighSchoolWish highSchoolWish) {

		if (null == highSchoolWish.getGzy11()) {

		}
		if ("*".equals(highSchoolWish.getGtszy()) || "".equals(highSchoolWish.getGtszy())) {
			highSchoolWish.setGtszy("");
			highSchoolWish.setGtszye("");
		}
		if ("*".equals(highSchoolWish.getGytzy()) || "".equals(highSchoolWish.getGytzy())) {
			highSchoolWish.setGytzy("");
			highSchoolWish.setGytzye("");
		}
		if ("".equals(highSchoolWish.getGylzy())) {
			highSchoolWish.setGylzy("");
		}
		if ("".equals(highSchoolWish.getGzy21())) {
			highSchoolWish.setGzy21("");
		}
		if ("".equals(highSchoolWish.getGzy22())) {
			highSchoolWish.setGzy22("");
		}
		if ("".equals(highSchoolWish.getGzy23())) {
			highSchoolWish.setGzy23("");
		}
		if ("".equals(highSchoolWish.getGzy24())) {
			highSchoolWish.setGzy24("");
		}
		if ("".equals(highSchoolWish.getGzy31())) {
			highSchoolWish.setGzy31("");
		}
		if ("".equals(highSchoolWish.getGzy32())) {
			highSchoolWish.setGzy32("");
		}
		if ("".equals(highSchoolWish.getGzy33())) {
			highSchoolWish.setGzy33("");
		}
		if ("".equals(highSchoolWish.getGzy34())) {
			highSchoolWish.setGzy34("");
		}
		return highSchoolWish;
	}

	public HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
		} catch (Exception e) {
		}
		return session;
	}

	public HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return attrs.getRequest();
	}

	/**
	 * 获取当前访问URL路径
	 * 
	 * @return
	 */
	public String getCurrentUrl(HttpServletRequest request) {
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getServletPath();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		}
		// log.debug(url);
		return url;

	}

	// pdf文件
	// TODO test
	public Boolean tranPdf(Object copyRightsVo) {
		// 模板地址
		String filePath = "templateC.pdf";
		// 填完信息后生成新的模板地址
		String toPath = "templateOL" + ".pdf";
		try {
			System.out.println(filePath);
			PdfDocument pdfDoc = new PdfDocument(new PdfReader(filePath), new PdfWriter(toPath));
			PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true);
			pdfAcroForm.getField("fileName").setValue("小编");
			pdfAcroForm.getField("applicant").setValue("ol");
			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
			String cmmitTime = simpleDateFormat.format(date);
			pdfAcroForm.getField("time").setValue(cmmitTime);
			// pdfAcroForm.getField("hashValue").setValue(copyRightsVo.getHashValue());
			pdfAcroForm.flattenFields();
			pdfDoc.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 根据PDF模板生成PDF文件
	 * 
	 * @param sourceFile
	 *            原模板文件
	 * @param targetFile
	 *            动态输入写入的文件
	 * @param fieldMap
	 *            动态数据值
	 */
	public static void toPDFWriteValue(String sourceFile, String fileName, String targetFilePath,
			Map<String, Object> fieldMap) throws Exception {

		FileOutputStream fos = null;
		try {
			com.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(sourceFile);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			// PdfStamper ps = new PdfStamper(reader, bos);
			PdfStamper ps = new PdfStamper(reader, bos);
			AcroFields s = ps.getAcroFields();
			// 解决中文
			com.itextpdf.text.pdf.BaseFont bfChinese = com.itextpdf.text.pdf.BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
					"UTF-8", false);
			//com.itextpdf.text.pdf.BaseFont bfChinese = com.itextpdf.text.pdf.BaseFont.createFont("STSong-Light",
			//		"UniGB-UCS2-H", false);
			s.addSubstitutionFont(bfChinese);
			// 判断写入文件是否存在，不存在创建
			File file = new File(targetFilePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			String fileSavePath = targetFilePath + fileName;
			File file1 = new File(fileSavePath);
			if (!file1.exists()) {
				file1.createNewFile();
			}

			// 将值封装至map中
			for (String key : fieldMap.keySet()) {
				// 遍历赋值
				s.setField(key, fieldMap.get(key).toString());
			}
			ps.setFormFlattening(true);
			
//            Document doc = new Document();  
//            PdfCopy copy = new PdfCopy(doc, fos);  
//            doc.open();  
//            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);  
//            copy.addPage(importPage);  
//            doc.close();
            
			ps.close();
			fos = new FileOutputStream(fileSavePath);
			fos.write(bos.toByteArray());
		} catch (FileNotFoundException e) {

			// log.error("生成PDF文件异常", e);
		} catch (Exception e) {
			// log.error("生成PDF文件异常", e);
		} finally {
			if (null != fos) {
				fos.close();
			}
		}
	}
}
